package com.weipeep.common.mail;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.*;

import javafx.util.Pair;
import org.apache.commons.collections.map.HashedMap;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailConfig emailConfig;
    @Resource
    private JavaMailSender mailSender;

    public void sendSimpleMail(String sendTo, String title, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(emailConfig.getEmailFrom());
        message.setTo(sendTo);
        message.setSubject(title);
        message.setText(content);
        mailSender.send(message);
    }
    public void sendHtmlMail(String sendTo, String title, String content){
        MimeMessage mailMessage = mailSender.createMimeMessage();
        String nick = null;
        try{
            nick=javax.mail.internet.MimeUtility.encodeText("一号轴承网");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
                "UTF-8");
        try {
            messageHelper.setFrom(new InternetAddress(nick+" <"+emailConfig.getEmailFrom()+">"));
            messageHelper.setTo(sendTo);
            messageHelper.setSubject(title);
            messageHelper.setText(content,true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(mailMessage);
    }

    public void sendAttachmentsMail(String sendTo, String title, String content, List<Pair<String, File>> attachments) {

        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(emailConfig.getEmailFrom());
            helper.setTo(sendTo);
            helper.setSubject(title);
            helper.setText(content);

            for (Pair<String, File> pair : attachments) {
                helper.addAttachment(pair.getKey(), new FileSystemResource(pair.getValue()));
            }
        } catch (Exception e) {

        }

        mailSender.send(mimeMessage);
    }

}
